<?php


namespace app\Activity\controller;


use app\activity\model\Activity;
use app\activity\model\ActivityItem;
use app\activity\model\ActivityItemRecord;
use app\activity\model\ActivityItemRecord as ActivityItemRecordModel;
use app\activity\model\ActivityItemsInActivity as ActivityItemsInActivityModel;
use app\activity\model\ActivityUserRecord;
use app\activity\model\ActivityUserRecord as ActivityUserRecordModel;
use app\ApiRest;
use app\card\model\User;
use app\card\model\UserInfo;
use think\facade\Db;

class WxAppActivityUserRecord extends ApiRest
{
    public function getSignItemByActivity()
    {
        $activity_id = $this->_param['activity_id'];
        $m_item_in_activity = new ActivityItemsInActivityModel();
        $items_in_activity  = $m_item_in_activity->field('title')->where([['activity_id', '=', $activity_id], ['status', '=', 1]])->select()->toArray();

        $titles = array_column($items_in_activity, 'title');
        $m_item = new ActivityItem();
        $items  = $m_item->field('id,title, is_phone')->where([['title', 'in', $titles], ['status', '=', 1], ['uniacid', '=', $this->_uniacid]])->select()->toArray();
        $item_map  = [];
        foreach ($items as $item) {
            $item_map[$item['title']] = $item['is_phone'];
        }



        foreach ($items_in_activity as $k => $v) {
            $items_in_activity[$k]['is_phone'] = $item_map[$v['title']] ?? 0;
            $items_in_activity[$k]['id']       = $m_item->where(['title'=>$v['title']])->value('id');
        }

        return $this->success($items_in_activity);
    }

    /**
     *
     * 活动报名：
     * 1 在ims_lb_activity_user_record表中记录user_id和acticity_id的关系
     * 2 修改活动表的sign_number
     * 3 在ims_lb_activity_item_record表中记录user_id填写的报名内容
     *   $item_records 为一个json， 格式如下 ：
     *   [
     * {"item_id": 233, "title" : "姓名", "content" : "张三", "is_phone" : 0},
     * {"item_id": 234, "title" : "手机号码", "content" : "15700316958", "is_phone" : 1}
     * ]
     */
    public function signOneActivity()
    {
        $time = time();
        $user_id = $this->_user_id;

        //用于接口测试的参数 --- onlyForTestUserId
        if ($this->_user_id === null && isset($this->_input['onlyForTestUserId'])) {
            $user_id = $this->_input['onlyForTestUserId'];
        }

        $staff_id     = $this->_input['staff_id'];
        $activity_id  = $this->_input['activity_id'];
        $item_records = $this->_input['item_records'];
        $uniacid      = $this->_uniacid;

        $m_activity    = new Activity();
        $m_user_record = new ActivityUserRecord();
        $m_item_record = new ActivityItemRecord();


        $active = $m_activity->where(['id' => $activity_id])->find();
        if(empty($active)){
            return $this->error('活动未找到');
        }

        if($active['sign_number']>=$active['sign_limit']){
            return $this->error('报名人数已满');
        }

        if ($user_id === null) {
            return $this->error('user_id is required');
        }
        if ($m_user_record->countByFilter([
            'activity_id' => $activity_id,
            'user_id' => $user_id])
        ) {
            return $this->success(lang('this activity has signed'));
        }

        $rst = $m_user_record->save([
            'activity_id' => $activity_id,
            'user_id'     => $user_id,
            'uniacid'     => $uniacid,
            'staff_id'    => $staff_id,
            'create_time' => $time,
            'update_time' => $time
        ]);

        foreach ($item_records as &$item_record) {
            $item_record['user_id'] = $user_id;
            $item_record['uniacid'] = $uniacid;
            $item_record['create_time'] = $time;
            $item_record['update_time'] = $time;
            $item_record['activity_id'] = $activity_id;
            $item_record['item_id'] = 0;
        }

        $rest = $m_item_record->saveAll($item_records);
        if(!$rst||!$rest){
            return $this->error('save item records error!!!');
        }

//        try {
//            $m_item_record->saveAll($item_records);
//        } catch (\Exception $exception) {
//            return $this->error('save item records error!!!');
//        }

        $rst && $m_activity->where(['id' => $activity_id])->inc('sign_number', 1)->update();
        return $this->success($rst);

    }


    public function mySignActivity()
    {
        $param = $this->_param;
        $activity_status = $param['activity_status'] ?? 0;

        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );
        //设置页码
        if (isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        //设置每页的数据
        if (isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];


        //准备分页数据
        $filterForRecord = [
            ['r.uniacid', '=', $this->_uniacid],
            ['r.user_id', '=', $this->_user_id ?? $this->_param['onlyForTestUserId'] ?? null],
        ];

        $filterForActivity = [['a.uniacid', '=', $this->_uniacid]];

        $nowTime = time();
        switch ($activity_status) {
            case 1:
                $filterForActivity = [
                    ['a.uniacid', '=', $this->_uniacid],
                    ['a.start_time', '>=', $nowTime]
                ];
                break;
            case 2:
                $filterForActivity = [
                    ['a.uniacid', '=', $this->_uniacid],
                    ['a.start_time', '<', $nowTime],
                    ['a.end_time', '>', $nowTime],
                ];
                break;
            case 3:
                $filterForActivity = [
                    ['a.uniacid', '=', $this->_uniacid],
                    ['a.end_time', '<=', $nowTime],
                ];
                break;
        }

        $page_config['total'] = Db::name('lb_activity_user_record')->alias('r')
            ->where($filterForRecord)
            ->join('lb_activity_activity a', 'r.activity_id = a.id')
            ->where($filterForActivity)
            ->count();

        $signActivity = Db::name('lb_activity_user_record')->alias('r')
            ->where($filterForRecord)
            ->join('lb_activity_activity a', 'r.activity_id = a.id')
            ->field(['a.id' => 'activity_id', 'r.id' => 'record_id'])
            ->field('a.cover, a.title, a.start_time, a.end_time, a.sign_start_time, a.sign_end_time, a.sign_limit, a.sign_number,  r.staff_id, r.is_sign_in')
            ->where($filterForActivity)
            ->order('record_id', 'desc')
            ->select()->toArray();

        foreach ($signActivity as $k => $rst) {
            $sign_start_time = $rst['sign_start_time'];
            $sign_end_time = $rst['sign_end_time'];
            $start_time = $rst['start_time'];
            $end_time = $rst['end_time'];
            $sign_limit = $rst['sign_limit'];
            $sign_number = $rst['sign_number'];
            $signActivity[$k]['sign_status'] = $this->_getSignStatus($sign_start_time, $sign_end_time, $sign_limit, $sign_number);
            $signActivity[$k]['type'] = $this->_getActivityStatus($start_time, $end_time, $sign_limit, $sign_number);
            $signActivity[$k]['start_time'] = date('Y-m-d H:i', $rst['start_time']);
            $signActivity[$k]['end_time'] = date('Y-m-d H:i', $rst['end_time']);
        }

        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if (($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        //设置返回参数
        $result = $page_config;
        //返回数据
        $signActivity = transImagesOne($signActivity, ['cover']);
        $result['data'] = $signActivity;


        return $this->success($result);

    }

    //核销签到
    public function signIn()
    {
        $record_id = $this->_param['record_id'] ?? null;
        $user_id = $this->_user_id ?? $this->_param['onlyForTestUserId'] ?? null;

        if (!UserInfo::where([['fans_id', '=', $user_id], ['is_staff', '=', 1]])->count()) {
            return $this->error("该用户不是员工");
        }
        $m_record = new ActivityUserRecord();
        $record = $m_record->where(['id' => $record_id,'is_sign_in'=>0])->find();
        if(empty($record)){
            return $this->error("活动已经核销");
        }
        $rst    = $m_record->where(['id' => $record_id])->update(['is_sign_in' => 1]);
        return $this->success($rst);
    }

    //核销二维码
//  public function activityRecordSignInQr()
//  {
//      $record_id = $this->_param['record_id'] ?? null;
//      $activity_id = $this->_param['activity_id'] ?? null;
//      if ($record_id === null || $activity_id === null) {
//          return $this->error("参数错误");
//      }
//
//
//      //生成文章二维码
//      $qrData = [
//          'record_id' =>  $record_id,
//          'activity_id' =>  $activity_id,
//      ];
//      $src = Cache::get("$record_id-activity_record_sign_qr" ,$this->_uniacid);
//
//      if(!$src){
//          $data  = longbingCreateWxCode($this->_uniacid,$qrData,'activity/pages/staff/sign');
//          $data  = transImagesOne($data ,['qr_path'] ,$this->_uniacid);
//          $src   = $data['qr_path'];
//
//          Cache::set("$record_id-activity_record_sign_qr", $data['qr_path']);
//      }
//      return $this->success(['src' => $src]);
//  }

    public function activityRecordSignInQr()
    {
        $record_id = $this->_param['record_id'] ?? null;
        $activity_id = $this->_param['activity_id'] ?? null;
        if ($record_id === null || $activity_id === null) {
            return $this->error("参数错误");
        }


        //生成文章二维码
        $qrData = [
            'record_id' =>  $record_id,
            'activity_id' =>  $activity_id,
        ];
        $src = getCache("$record_id-activity_record_sign_qr", $this->_uniacid);


        if(!$src){
            $data  = longbingCreateWxCode($this->_uniacid,$qrData,'activity/pages/staff/sign');
            $data  = transImagesOne($data ,['qr_path'] ,$this->_uniacid);


            $src = $data['qr_path'];
            setCache("$record_id-activity_record_sign_qr", $data['qr_path'], 3600, $this->_uniacid);
        }


        return $this->success(['src' => $src]);
    }



    //核销签到详情列表
    public function activityRecordSignInQrList()
    {
        $record_id = $this->_param['record_id'] ?? null;
        $activity_id = $this->_param['activity_id'] ?? null;
        if ($record_id === null || $activity_id === null) {
            return $this->error("参数错误");
        }

        $param = $this->_param;
        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );
        //设置页码
        if (isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        //设置每页的数据
        if (isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];


        $model = new ActivityUserRecordModel();

        $filter = [
            ['r.activity_id', '=', $activity_id],
            ['r.status', '=', 1],
            ['r.is_sign_in', '=', 1],
        ];

        $page_config['total'] = $model->alias('r')
            ->join('longbing_card_user u', 'r.user_id=u.id')
            ->where($filter)
            ->count();

        $rsts = $model->alias('r')
            ->join('longbing_card_user u', 'r.user_id=u.id')
            ->where($filter)
            ->field(['u.nickName', 'u.avatarUrl', 'r.id','u.id as user_id'])
            ->page($page_config['page'], $page_config['page_count'])->order('id', 'desc')->select()->toArray();

        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if (($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        //设置返回参数
        $result = $page_config;
        //返回数据
        $rsts = transImagesOne($rsts, ['avatarUrl']);

        if(!empty($rsts)){
            //内容记录模型
            $m_item_record = new ActivityItemRecordModel();

            foreach ($rsts as &$v){

                $dis = [

                    ['uniacid','=',$this->_uniacid],

                    ['activity_id','=',$activity_id],

                    ['is_phone','>',0],

                    ['user_id','=',$v['user_id']],

                ];

                $record_list    = $m_item_record->where($dis)->select()->toArray();

                $record_content = '';

                if(!empty($record_list)){

                    foreach ($record_list as $value){

                        $record_content.=$value['title'].':'.$value['content'].'   ';

                    }
                }
                $v['record_content'] = $record_content;
            }
        }

        $result['data'] = $rsts;

        $m_activity    = new Activity();

        $activity_info = $m_activity->field(['cover','start_time', 'end_time', 'sign_limit', 'sign_number', 'title','id'])->where('id', '=', $activity_id)->find()->toArray();

        $activity_info['start_time'] = date('Y-m-d H:i', $activity_info['start_time']?? 0);

        $activity_info['end_time']   = date('Y-m-d H:i', $activity_info['end_time'] ?? 0);

        $activity_info = transImagesOne($activity_info, ['cover']);
        //查看是否签到
        $filter = [
            ['activity_id', '=', $activity_id],
            ['status', '=', 1],
            ['is_sign_in', '=', 1],
            ['user_id', '=', $this->getUserId()],
        ];

        $user_record = $model->where($filter)->find();

        $activity_info['is_sign_in'] = !empty($user_record)?1:0;

        $result['activity_info']     = $activity_info;

        return $this->success($result);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-06-17 16:20
     * @功能说明:报名详情
     */
    public function recordInfo(){

        $param = $this->_param;

        $filter['r.id'] = $param['record_id'];

        $model = new ActivityUserRecordModel();

        $m_item_record = new ActivityItemRecordModel();

        $rsts = $model->alias('r')
            ->join('longbing_card_user u', 'r.user_id=u.id')
            ->where($filter)
            ->field(['u.nickName', 'u.avatarUrl', 'r.id','u.id as user_id','r.create_time','r.activity_id'])
            ->find()
            ->toArray();

        $rsts['create_time'] = date('Y-m-d H:i:s',$rsts['create_time']);


        $dis = [
            ['uniacid','=',$this->_uniacid],

            ['activity_id','=',$rsts['activity_id']],

//            ['is_phone','>',0],

            ['user_id','=',$rsts['user_id']],
        ];

        $record_list = $m_item_record->where($dis)->select()->toArray();

        $rsts['record_list'] = $record_list;

        return $this->success($rsts);
    }


    public function activityDetail()
    {
        $record_id = $this->_param['record_id'];

        $m_record = new ActivityUserRecord();
        $record = $m_record->field('user_id, staff_id, activity_id, is_sign_in')->where(['id' => $record_id])->find();

        $m_activity = new Activity();
        $activity = $m_activity->field('id, cover, title, start_time, end_time, sign_limit, sign_number')->where(['id' => $record['activity_id']])->find();
        $activity['type'] = $this->_getActivityStatus($activity['start_time'], $activity['end_time'], $activity['sign_limit'], $activity['sign_number']);
        $m_item_record = new ActivityItemRecordModel();
        $item_records = $m_item_record->getListByUserIdsAndActivityId([$record['user_id']], $record['activity_id']);

        $m_user = new User();
        $user = $m_user->where(['id' => $record['staff_id']])->find() ?? [];
        $data = [
            'id' => $activity['id'],
            'record_id' => $record_id,
            'cover' => $activity['cover'],
            'title' => $activity['title'],
            'start_time' => date('Y-m-d H:i', $activity['start_time']),
            'end_time' => date('Y-m-d H:i', $activity['end_time']),
            'item_records' => $item_records,
            'staff_id' => $record['staff_id'],
            'avatar' => $user['avatarUrl'] ?? '',
            'nickName' => $user['nickName'] ?? '',
            'type' => $activity['type'],
            'is_sign_in' => $record['is_sign_in'],
            'sign_limit' => $activity['sign_limit'],
            'remain_days' => $this->lb_friendly_date_v2($activity['start_time']) ? '还剩' . $this->lb_friendly_date_v2($activity['start_time']) . '活动开始' : ''
        ];
        return $this->success(transImagesOne($data, ['avatar', 'cover']));
    }


    private function lb_friendly_date_v2($sTime)
    {
        if (!$sTime)
            return '';
        //sTime=源时间，cTime=当前时间，dTime=时间差
        $cTime = time();
        $dTime = $cTime - $sTime;

        if ($dTime > 0)
        {//活动结束
            return '';
        }

        $dTime = abs($dTime);
        $dDay = intval($dTime / 3600 / 24);
        $dYear = intval(date("Y", $cTime)) - intval(date("Y", $sTime));

        if ($dTime < 60)
        {
            return $dTime . '秒';
        } elseif ($dTime < 3600)
        {
            return intval($dTime / 60) . '分钟';
        } elseif ($dTime >= 3600 && $dDay == 0)
        {
            return intval($dTime / 3600) . '小时';
        } elseif ($dDay > 0 && $dDay <= 7)
        {
            return intval($dDay) . '天';
        } elseif ($dDay > 7 && $dDay <= 30)
        {
            return intval($dDay / 7) . '周';
        } elseif ($dDay > 30)
        {
            return intval($dDay / 30) . '个月';
        } elseif ($dYear > 1)
        {
            return intval($dYear) . '年';
        }
        return "";
    }


    public function listByActivity()
    {
        $param = $this->_param;

        if (!isset($param['activity_id'])) {
            return $this->error("activity_id is required");
        }
        $activity_id = $param['activity_id'];

        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );
        //设置页码
        if (isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        //设置每页的数据
        if (isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];


        //准备分页数据
        $activity_user_records = [];

        $filter['uniacid'] = $this->_uniacid;
        $filter['activity_id'] = $activity_id;

        $filter['staff_id'] = $this->getUserId();


        $model = new ActivityUserRecordModel();

        $page_config['total'] = $model->countByFilter($filter);

        $records_tmp = $model->getListByFilter($filter, $page_config);

        foreach ($records_tmp as $record) {
            $activity_user_records[$record['user_id']] =
                [
                    'user_id'     => $record['user_id'],
                    'create_time' => $record['create_time'],
                    'avatarUrl'   => !empty($record['userInfo']['avatarUrl'])?$record['userInfo']['avatarUrl']:'',
                    'nickName'    => !empty($record['userInfo']['nickName'])?$record['userInfo']['nickName']:'',
                    'is_sign_in'  => $record['is_sign_in']
                ];
        }

        $m_item_record = new ActivityItemRecordModel();

        $record_items = $m_item_record->getListByUserIdsAndActivityId(array_keys($activity_user_records), $activity_id);
        foreach ($record_items as $item) {
            $activity_user_records[$item['user_id']]['item_records'][] = $item;
            if ($item['is_phone']) {
                $activity_user_records[$item['user_id']]['phone'][] = $item['content'];
            }
        }

        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if (($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        //设置返回参数
        $result = $page_config;
        //返回数据
        $result['data'] = array_values($activity_user_records);

        return $this->success($result);

    }


    private function _getSignStatus($sign_start_time, $sign_end_time, $sign_limit, $sign_number)
    {
        if ($sign_number >= $sign_limit)
        {
            return 3;
        }
        $end_pre_day = strtotime('-1 day', strtotime(date('Y-m-d', (int)$sign_end_time)));
        $status = -1;
        if ($sign_start_time > $sign_end_time)
        {
            return $status;
        }

        $now = time();
        if ($now < $sign_start_time)
        {
            $status = 0; //未开始
        }

        if ($now >= $sign_start_time && $now < $sign_end_time)
        {
            $status = 1; //报名中
        }

        if ($now >= $sign_start_time && $now < $sign_end_time && $now >= $end_pre_day)
        {
            $status = 2; // 报名即将结束
        }

        if ($now >= $sign_end_time)
        {
            $status = 3; //报名结束
        }

        return $status;
    }

    private function _getActivityStatus($start_time, $end_time, $sign_limit, $sign_number)
    {
//        if ($sign_number >= $sign_limit) {
//            return 3;
//        }
//        $end_pre_day = strtotime('-1 day', strtotime(date('Y-m-d', (int)$end_time)));
        $status = -1;
        if ($start_time > $end_time)
        {
            return $status;
        }

        $now = time();
        if ($now < $start_time)
        {
            $status = 1; //未开始
        }

        if ($now >= $start_time && $now < $end_time)
        {
            $status = 2; //活动中
        }
//
//        if ($now >= $start_time && $now < $end_time && $now >= $end_pre_day) {
//            $status = 2; // 活动即将结束
//        }

        if ($now >= $end_time)
        {
            $status = 3; //报名结束
        }

        return $status;
    }
}